﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;

namespace CjcPhotoPrint.Exporters
{
	public class Save : Exporter
	{
		public override void Export( IEnumerable<Transformable> transformables, Dispatcher dispatcher )
		{
			var dialog = new SaveFileDialog
			{
				Filter = "Image files (*.jpg)|*.jpg|*.bmp)|*.bmp|All Files (*.*)|*.*",
				DefaultExt = ".jpg",
				RestoreDirectory = true
			};

			if ( (bool)dialog.ShowDialog() )
			{
				var images = GetImages( transformables ).ToArray();

				foreach ( var transformable in transformables )
				{
					var image = new TransformedImage { Drawing = transformable.Drawing };
					var size = new Size( 3000, 3000 );

					image.Measure( size );
					image.Arrange( new Rect( new Point(), image.DesiredSize ) );

					var renderSize = image.RenderSize;
					var bitmap = new RenderTargetBitmap( (int)renderSize.Width, (int)renderSize.Height, 96, 96, PixelFormats.Pbgra32 );

					bitmap.Render( image );

					var extension = Path.GetExtension( dialog.SafeFileName );

					var filename = Path.Combine(
						Path.GetDirectoryName( dialog.FileName ),
						Path.GetFileNameWithoutExtension( dialog.SafeFileName )
							+ "_"
							+ Path.GetFileNameWithoutExtension( transformable.Name ) + extension );

					using ( var file = File.Create( filename ) )
					{
						switch ( extension.ToLower() )
						{
							case ".jpg":
							case ".jpeg":
								{
									var encoder = new JpegBitmapEncoder();
									encoder.Frames.Add( BitmapFrame.Create( bitmap ) );
									encoder.Save( file );
									break;
								}

							case ".png":
								{
									var encoder = new PngBitmapEncoder();
									encoder.Frames.Add( BitmapFrame.Create( bitmap ) );
									encoder.Save( file );
									break;
								}
						}
					}
				}
			}
		}

		protected IEnumerable<KeyValuePair<string, TransformedImage>> GetImages(
			IEnumerable<Transformable> transformables )
		{
			foreach ( var transformable in transformables )
			{
				var image = new TransformedImage { Drawing = transformable.Drawing };
				var size = new Size( double.PositiveInfinity, double.PositiveInfinity );

				image.Measure( size );
				image.Arrange( new Rect( new Point(), image.DesiredSize ) );

				yield return new KeyValuePair<string, TransformedImage>( transformable.Name, image );
			}
		}
	}
}